package com.ssyt.hiring.talent.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ssyt.hiring.common.Constants;
import com.ssyt.hiring.common.util.AppUtil;
import com.ssyt.hiring.company.entity.ApplicationEntity;
import com.ssyt.hiring.company.service.ApplicationService;
import com.ssyt.hiring.talent.entity.TalentEntity;
import com.ssyt.hiring.talent.service.TalentService;

public class TalentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private TalentService talentService = new TalentService();
	private ApplicationService applicationService = new ApplicationService();

	public TalentServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(Constants.ENCODE_UTF8);
		String command = request.getParameter("command");
		if ("toLoginUI".equals(command)) {
			toLoginUI(request, response);
		} else if ("login".equals(command)) {
			login(request, response);
		} else if ("toRegisterUI".equals(command)) {
			toRegisterUI(request, response);
		} else if ("add".equals(command)) {
			add(request, response);
		} else if ("logout".equals(command)) {
			logout(request, response);
		} else if ("preUpdate".equals(command)) {
			preUpdate(request, response);
		} else if ("update".equals(command)) {
			update(request, response);
		} else if ("updatePwd".equals(command)) {
			updatePwd(request, response);
		} else if ("main".equals(command)) {
			main(request, response);
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void updatePwd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String oldPassword = request.getParameter("password1");
		String newPassword = request.getParameter("password2");

		int row = talentService.updatePwd(oldPassword, newPassword, id);

		response.sendRedirect("TalentServlet?command=main&row=" + row);
	}

	/**
	 * 执行信息修改
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		int age = Integer.parseInt(request.getParameter("age"));
		int gender = Integer.parseInt(request.getParameter("gender"));
		String[] hobbys = request.getParameterValues("hobby");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < hobbys.length; i++) {
			if (i == hobbys.length - 1) {
				sb.append(hobbys[i]);
			} else {
				sb.append(hobbys[i] + "|");
			}
		}
		List<Object> list = new ArrayList<>();
		list.add(name);
		list.add(phone);
		list.add(email);
		list.add(age);
		list.add(gender);
		list.add(sb.toString());
		list.add(id);
		int row = talentService.update(list);
		if (row > 0) {
			TalentEntity talent = talentService.preUpdate(id);
			request.getSession().setAttribute("talent", talent);
			response.sendRedirect("TalentServlet?command=main&row=" + row);
		}

	}

	/**
	 * 修改前查询
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void preUpdate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int id = AppUtil.getTalentId(request, response);
		TalentEntity talent = talentService.preUpdate(id);
		if (talent != null) {
			System.out.println(talent);
			request.setAttribute("tal", talent);
			request.getRequestDispatcher("/WEB-INF/view/talent/update.jsp")
					.forward(request, response);
		}
	}

	/**
	 * 注销
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getSession().invalidate();
		response.sendRedirect("PositionServlet?command=queryAll");

	}

	/**
	 * 求职者注册
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void add(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String validateCode = request.getParameter("validateCode");
		String vcode = (String) request.getSession().getAttribute("vcode");
		if (vcode.equals(validateCode)) {
			String code = request.getParameter("code");
			TalentEntity talent = talentService.queryByCode(code);
			if (talent != null) {
				request.setAttribute("msg", "账号已被注册，请输入新的账号！");
				request.getRequestDispatcher(
						"/WEB-INF/view/talent/register.jsp").forward(request,
						response);
			}
			List<Object> list = new ArrayList<>();
			String password = request.getParameter("password");
			String name = request.getParameter("name");
			String phone = request.getParameter("phone");
			String email = request.getParameter("email");
			int age = Integer.parseInt(request.getParameter("age"));
			int gender = Integer.parseInt(request.getParameter("gender"));
			String[] hobbys = request.getParameterValues("hobby");
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < hobbys.length; i++) {
				if (i == hobbys.length - 1) {
					sb.append(hobbys[i]);
				} else {
					sb.append(hobbys[i] + "|");
				}
			}
			list.add(code);
			list.add(password);
			list.add(name);
			list.add(phone);
			list.add(email);
			list.add(age);
			list.add(gender);
			list.add(sb.toString());

			int row = talentService.add(list);
			if (row > 0) {
				response.sendRedirect("TalentServlet?command=toLoginUI");
			} else {
				request.setAttribute("msg", "注册失败，请重试！");
				request.getRequestDispatcher(
						"/WEB-INF/view/talent/register.jsp").forward(request,
						response);
			}
		} else {
			request.setAttribute("msg", "验证码输入错误！");
			request.getRequestDispatcher("/WEB-INF/view/talent/register.jsp")
					.forward(request, response);
		}
	}

	/**
	 * 跳转到注册界面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void toRegisterUI(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/talent/register.jsp")
				.forward(request, response);
	}

	/**
	 * 求职者登录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String validateCode = request.getParameter("validateCode");
		String vcode = (String) request.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (vcode.equals(validateCode)) {
			String code = request.getParameter("code");
			String password = request.getParameter("password");
			TalentEntity talent = talentService.login(code, password);

			if (talent != null) {
				request.getSession().setAttribute("talent", talent);
				response.sendRedirect("TalentServlet?command=main");
			} else {
				request.setAttribute("msg", "用户名或密码错误！");
				request.getRequestDispatcher("/WEB-INF/view/talent/login.jsp")
						.forward(request, response);
			}
		} else {
			request.setAttribute("msg", "验证码输入错误！");
			request.getRequestDispatcher("/WEB-INF/view/talent/login.jsp")
					.forward(request, response);
		}
	}

	/**
	 * 跳转到登录界面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void toLoginUI(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		request.getRequestDispatcher("/WEB-INF/view/talent/login.jsp").forward(
				request, response);
	}

	/**
	 * 到主页时的查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void main(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String rowStr = request.getParameter("row");
		// 非登录操作
		if (rowStr != null) {
			int row = Integer.parseInt(rowStr);
			if (row == 1) {
				request.setAttribute("success", "操作成功！");
			} else {
				request.setAttribute("error", "操作失败！");
			}
		}
		int id = AppUtil.getTalentId(request, response);
		// 求职列表
		List<ApplicationEntity> applicationList = applicationService.list(id);
		request.setAttribute("applicationList", applicationList);
		request.getRequestDispatcher("/WEB-INF/view/talent/main.jsp").forward(
				request, response);
	}

}
